<template>
  <div style="height: 100%">
    <AHMF
      :asideWidth="300"
      :rightTitleShow="false"
      :AShow="true"
      leftTitle="项目名称"
      :FShow="true"
    >
      <template #aside>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          highlight-current
          node-key="id"
          ref="tree"
          v-loading="treeLoading"
          :render-content="renderContent"
        ></el-tree>
      </template>
      <template #header>
        <div class="header-container">
          <div class="header-left">
            <div class="header-left-title">基础信息</div>
            <div class="header-left-content">
              <div class="field" data-label="项目名称:">
                <span style="color: #3c9cff">{{
                  detailObj.projectName || "--"
                }}</span>
              </div>
              <div class="field" data-label="评估年份:">
                <span style="color: #3c9cff"
                  >{{ detailObj.startTime || "--" }} ~
                  {{ detailObj.endTime || "--" }}</span
                >
              </div>
            </div>
          </div>
          <!-- 文件下载按钮 -->
          <el-button type="primary" size="small" @click="exportExcel"
            >文件下载</el-button
          >
        </div>
      </template>
      <template #main>
        <SpreadSheet
          style="height: 100%; width: 100%"
          ref="Sheet"
          SheetName="Sheet1"
          :File="file"
          :Headers="headers"
          :ColumnWidth="200"
          :Records="records"
          :onlyRead="true"
          @getFileId="getFileId"
        ></SpreadSheet>
      </template>
      <template #footer>
        <div style="display: flex; justify-content: flex-start; width: 100%">
          <el-radio-group v-model="tabPosition" size="small">
            <el-radio-button
              :label="item.templateName"
              v-for="item in tableData"
              :key="item.evaluateId"
              @click.native="changeFile(item)"
              >{{ item.templateName || "附件名称" }}</el-radio-button
            >
          </el-radio-group>
        </div>
      </template>
    </AHMF>
  </div>
</template>
<script>
import AHMF from "@/components/topSearcher/AHMF.vue";
import ETable from "@/components/ETable";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import {
  ProjectEvalInfoApi,
  ProjectEvalTemplateApi,
  ProjectEvalInfoByIdApi,
  ProjectEvalInfoModifyFileIdApi,
} from "@/api/evaluationPreview";
import { convertToTreeDataProject } from "@/utils/publicReq.js";
import { exportExcelFn } from "@/utils/publicReq";
export default {
  components: {
    AHMF,
    SpreadSheet,
    ETable,
  },

  data() {
    return {
      detailObj: {},
      searchForm: {
        evaluateId: "",
      },
      currentNode: null,

      tabPosition: "",
      tableLoading: false,
      treeLoading: false,
      file: null,
      ColumnCount: 999,
      RowCount: 999,
      headers: [],
      records: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },

      tableData: [],
      tableLoading: false,
      fileId: null,
      spreadsheetData: [],

      renderContent: function (h, { node, data, store }) {
        let addElement = arguments[0];
        if (data.type === "parent") {
          return addElement("span", [
            addElement("i", { class: "el-icon-folder-opened" }),
            addElement("span", "    "),
            addElement("span", arguments[1].node.label),
          ]);
        } else {
          return addElement("span", [
            addElement("i", { class: "el-icon-document" }),
            addElement("span", "    "),
            addElement("span", arguments[1].node.label),
          ]);
        }
      },
    };
  },
  async mounted() {
    this.tableLoading = true;
    this.treeLoading = true;
    this.treeData = await convertToTreeDataProject();
    this.treeLoading = false;
    if (this.treeData.length !== 0) {
      // 假设每个节点都有一个唯一的id作为node-key
      this.$nextTick(() => {
        setTimeout(async () => {
          this.$refs.tree.setCurrentNode(this.treeData[0]);
          await this.handleNodeClick(this.treeData[0]);
        });
      });
    }
  },

  methods: {
    changeFile(item) {
      this.$refs.Sheet.loadData(JSON.parse(item.excelJson) || []);
      console.log("changeFile", item);
      //当前选中的节点
      this.currentNode = item;
    },
    //把当前选中的文件对象移动到数组末尾,这样在点击文件下载的时候显示的还是当前的excelJson
    moveItemToEndById(array, targetId) {
      // 创建两个数组，一个用于存放不匹配的对象，另一个用于存放匹配的对象
      const uniqueItems = [];
      const duplicateItems = [];
      // 遍历数组
      array.forEach((item) => {
        if (item.id == targetId) {
          // 如果 id 匹配，将对象添加到 duplicateItems 数组
          duplicateItems.push(item);
        } else {
          // 否则，将对象添加到 uniqueItems 数组
          uniqueItems.push(item);
        }
      });
      // 使用扩展运算符将 duplicateItems 数组添加到 uniqueItems 数组的末尾
      const result = [...uniqueItems, ...duplicateItems];
      return result;
    },
    //为了让导出的json数据格式满足组件导出所需属性等等，需要把数据重新加载到sheet组件中，然后获取数据
    async updateTableDataWithSheets() {
      try {
        // 确保组件已经加载
        await this.$nextTick();

        // 检查 ref 是否存在
        if (!this.$refs.Sheet) {
          console.error("Sheet 组件未找到");
          return;
        }

        // 检查方法是否存在
        if (typeof xs.getData !== "function") {
          console.error("Sheet 组件没有 getData 方法");
          return;
        }

        // 使用 for...of 循环处理每个项目
        for (const item of this.tableData) {
          try {
            // 解析 JSON 数据
            const excelData = JSON.parse(item.excelJson || "[]");

            // 加载数据到 Sheet 组件
            if (typeof this.$refs.Sheet.loadData === "function") {
              await this.$refs.Sheet.loadData(excelData);
            } else {
              console.error("Sheet 组件没有 loadData 方法");
              continue;
            }

            // 获取数据并保存
            const sheetData = xs.getData();
            item.sheetData = sheetData || [];

            console.log(`已处理项目 ${item.name || item.id}:`, sheetData);
          } catch (error) {
            console.error("处理项目时出错:", error, item);
          }
        }
        console.log("更新后的 tableData:", this.tableData);
      } catch (error) {
        console.error("更新表格数据时出错:", error);
      }
    },

    async exportExcel() {
      // if (this.fileId) {
      //   exportExcelFn(this.fileId, this.fileName);
      //   return;
      // }
      let sheets = [];
      await this.updateTableDataWithSheets();
      let showSheets = this.moveItemToEndById(
        this.tableData,
        this.currentNode.id
      );
      console.log("showSheets", showSheets);
      showSheets.forEach(async (item) => {
        sheets.push(item.sheetData || []);
      });
      const flatArray = sheets.flat();
      setTimeout(() => {
        this.$refs.Sheet.exportExcel(this.fileName || "模板名称", flatArray);
      }, 0);
    },
    //获取文件id事件
    async getFileId(id) {
      console.log("文件id", id);
      if (id) {
        //去更新fileId
        let res = await ProjectEvalInfoModifyFileIdApi({
          id: this.searchForm.evaluateId,
          fileId: id,
        });
        if (res.data && res.data.bcode == 0) {
          this.$message.success("文件已上传");
        }
      }
    },
    //树节点选中
    async handleNodeClick(data) {
      this.tabPosition = "";
      console.log("树节点选中", data);
      if (data.pid == "" || data.pid == null) {
        this.tableData = [];
        this.searchForm.evaluateId = "";
        this.detailObj = {};
        this.$refs.Sheet.loadData([]);
        return;
      }

      this.fileName = data.name;
      this.searchForm.evaluateId = data.id;
      this.getData();
    },
    async getData() {
      this.tableLoading = true;
      ProjectEvalTemplateApi({
        evaluateId: this.searchForm.evaluateId,
      }).then(async (res) => {
        if (res.data && res.data.bcode == 0) {
          console.log("项目预览11", res.data);
          this.tableData = res.data.bdata.gdata || [];
          if (!this.tabPosition) {
            this.tabPosition = this.tableData[0].templateName;
            this.$nextTick(() => {
              this.$refs.Sheet.loadData(
                JSON.parse(this.tableData[0].excelJson) || []
              );
              this.currentNode = this.tableData[0];
            });
          }
        }
      });
      //详情查项目名称，评估年份,是否有文件id
      ProjectEvalInfoByIdApi(this.searchForm.evaluateId).then(async (res) => {
        if (res.data && res.data.bcode == 0) {
          console.log("项目预览", res.data);
          this.detailObj = res.data.bdata;
          this.fileId = res.data.bdata.fileId;
        }
      });
    },
  },
};
</script>
<style lang="scss" scope>
.el-footer {
  justify-content: flex-start;
}
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  width: 100%;
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  padding-right: 20px;
  .header-left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .header-left-title {
      display: flex;
      align-items: center;
      width: 46px;
      height: 59px;
      background-color: rgba(60, 156, 255, 1);
      color: #fff;
    }
    .header-left-content {
      display: flex;
      margin-left: 10px;
      .field {
        margin-left: 20px;
      }
      .field::before {
        content: attr(data-label);
        font-weight: bold; /* 加粗字体 */
        margin-right: 10px; /* 添加右边距 */
      }
    }
  }
}
</style>
